import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import service from '../mock/service'
import Router from '../router/index'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    name: 'xxxx',
    loginObj: {},
    healthyFormData: []
  },
  getters: {
    getLoginObj(state) {
      return state.loginObj
    },
    getHealthyFormData(state) {
      return state.healthyFormData
    }
  },
  mutations: {
    // store 中的数据用 commit mutatoins来改变
    changeData(state, obj) {
      state.loginObj = obj
    },
    changeLoginState(state, loginObj) {
      state.loginObj = loginObj
    },
    passHealthyData(state, obj) {
      state.healthyFormData = obj
    }
  },
  actions: {
    submitLogin(context, obj) {
      // 可以改成并发
      axios.get(service.url + '/login', {
        params: {
          username: obj.username,
          pwd: obj.pwd
        }
      }).then(res => {
        const isLoginPass = res.data
        const results = {
          data: obj,
          isPass: isLoginPass
        }
        // commit mutations
        context.commit('changeLoginState', results)
        if (isLoginPass) {
          axios.get(service.url + '/form', {
            params: {
              username: obj.username
            }
          }).then(res => {
            context.commit('passHealthyData', res.data)
            isLoginPass && Router.push('/home')
          }).catch(err => {
            console.log(err)
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // getHealthyForm (context, obj) {
    //   axios.get(service.url+'/form', {params: {
    //     username: obj.username,
    //   }}).then(res => {
    //     context.commit('passHealthyData',res.data)
    //   }).catch(err => {
    //     console.log(err)
    //   })
    // },
    saveHealthyForm(context, obj) {
      alert('保存成功')
    },
    // 用async来实现异步
    async getTodos({ commit }) {
      // const results = await axios.get('https://jsonplaceholder.typicode.com/posts')
      const results = {
        data: [1, 2, 3]
      }
      commit('changeData', results.data)
    }
  },
  modules: {

  }
})
